package com.depthsdata.coe.api;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.depthsdata.coe.dao.BusinessUnitDAOQueryBean;
import com.depthsdata.coe.service.BusinessUnitBean;
import com.depthsdata.coe.service.IBusinessUnitService;
import com.ourteam.frame.controller.AbstractCRUDServiceController;

@Controller
@CrossOrigin
@RequestMapping("/api/COE/businessUnit")
public class BusinessUnitManageAPI extends
		AbstractCRUDServiceController<com.depthsdata.coe.dao.BusinessUnitDAOQueryBean, com.depthsdata.coe.api.BusinessUnitSearchBean, BusinessUnitBean> {

	@Autowired
	private IBusinessUnitService businessUnitService;

	@Override
	protected BusinessUnitDAOQueryBean newQueryBean() {
		return new BusinessUnitDAOQueryBean();
	}

	@Override
	protected int queryCount(BusinessUnitDAOQueryBean queryBean) throws Exception {

		return businessUnitService.queryBusinessUnitCount(queryBean);
	}

	@Override
	protected BusinessUnitBean[] queryData(BusinessUnitDAOQueryBean queryBean) throws Exception {
		return businessUnitService.queryBusinessUnits(queryBean);
	}

	@Override
	protected void deleteData(long[] ids) throws Exception {

		businessUnitService.deleteBusinessUnits(ids);

	}

	@Override
	protected BusinessUnitBean getDataById(long id) throws Exception {
		return businessUnitService.getBusinessUnitById(id);
	}

	@Override
	protected void saveData(BusinessUnitBean dataBean) throws Exception {

		if (dataBean.getId() == 0) {
			businessUnitService.addNewBusinessUnit(dataBean);
		} else {
			businessUnitService.modifyBusinessUnit(dataBean);
		}

	}
	
	@RequestMapping("/list")
	@ResponseBody
	public BusinessUnitBean[] query(final @RequestParam(required=false) String businessNameName) throws Exception {

		BusinessUnitDAOQueryBean searchBean = new BusinessUnitDAOQueryBean();

		BusinessUnitDAOQueryBean.Criteria criteria = searchBean.createCriteria();
		
		criteria.andStatusEqualTo("available");

		if (StringUtils.isNoneBlank(businessNameName)) {
			criteria.andBusinessUnitNameLike(businessNameName);
		}

		return businessUnitService.queryBusinessUnits(searchBean);
	}

}
